from flask import Blueprint, request
from service.user_service import UserService
from utils.ResultUtil import Response
from model.User import User
user = Blueprint("user", __name__, url_prefix="/user")


@user.route('/list', methods=['GET'])
def user_list():
    return Response().success(UserService().list())


@user.route('/addUser', methods=['POST'])
def addUser():
    try:
        data = request.get_json()
        UserService().addUser(User.decode(data))
    except Exception as e:
        print("用户保存出现错误：{}".format(e))
        return Response().errorMsg(e)
    return Response().success()


@user.route('/update', methods=['POST'])
def updateUser():
    try:
        data = request.get_json()
        UserService().update(User.decode(data))
    except Exception as e:
        print("用户修改出现错误：{}".format(e))
        return Response().errorMsg(e)
    return Response().success()


@user.route('/login', methods=['POST'])
def login():
    try:
        data = request.get_json()
        user = UserService().login(data["username"], data["password"])
    except Exception as e:
        print("查询错误：{}".format(e))
        return Response().errorMsg(e)
    return Response().success(user)


@user.route('/deleteByNumber', methods=['GET'])
def findByUsername():
    try:
        number = request.args.get("number")
        UserService().deleteUser(number)
    except Exception as e:
        print("查询错误：{}".format(e))
        return Response().errorMsg(e)
    return Response().success()
